<?php
/**
 * 我的商城
 *
 * @好商城 (c) 2015-2018 33HAO Inc. (http://www.33hao.com)
 * @license    http://www.33 hao.c om
 * @link       交流群号：138182377
 * @since      好商城提供技术支持 授权请购买shopnc授权
 */



defined('In33hao') or exit('Access Invalid!');

class member_indexControl extends mobileMemberControl {

    public function __construct(){
        parent::__construct();
    }

    /**
     * 我的商城
     */
    public function indexOp() {
        $member_info = array();
        $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
        $member_info['user_name'] = $this->member_info['member_name'];
        $member_info['member_points'] = $this->member_info['member_points'];
        $member_info['avatar'] = getMemberAvatarForID($this->member_info['member_id']);
        $member_gradeinfo = Model('member')->getOneMemberGrade(intval($this->member_info['member_exppoints']));
        $member_info['level_name'] = $member_gradeinfo['level_name'];
        $member_info['favorites_store'] = Model('favorites')->getStoreFavoritesCountByMemberId($this->member_info['member_id']);
        $member_info['favorites_goods'] = Model('favorites')->getGoodsFavoritesCountByMemberId($this->member_info['member_id']);
        $area = explode(' ',$this->member_info['member_areainfo']);
        $member_info['area'] = $area[2];
        // 交易提醒
        $model_order = Model('order');
        $member_info['order_nopay_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'NewCount');
        $member_info['order_noreceipt_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'SendCount');
        $member_info['order_notakes_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'TakesCount');
        $member_info['order_noeval_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'EvalCount');
        
        // 售前退款
        $condition = array();
        $condition['buyer_id'] = $this->member_info['member_id'];
        $condition['refund_state'] = array('lt', 3);
        $member_info['return'] = Model('refund_return')->getRefundReturnCount($condition);
        $model =  Model();
        $store_info = $model->table('store')->where(['member_id'=>$this->member_info['member_id']])->find();
        $member_info['store_id'] = $store_info['store_id'] ? $store_info['store_id'] : 0;
        $member_info['store_class'] = $store_info['store_class'] ? $store_info['store_class'] : 0;
        $res = $model->table('agent')->field('id')->where(['member_id'=>$this->member_info['member_id']])->find();
        $member_info['agent_id'] = $res['id'] ? $res['id'] : 0;
        output_data(array('member_info' => $member_info));
    }

    /**
     * 我的推广
     */
    public function myPromotion1Op(){
        $model_mb_user_token = Model('mb_user_token');
        $key = $_POST['key'];
        if(empty($key)) {
            $key = $_GET['key'];
        }
        $mb_user_token_info = $model_mb_user_token->getMbUserTokenInfoByToken($key);
        output_data(array('member_info' => $mb_user_token_info));
    }

    /**
     * 我的资产
     */
    public function my_assetOp() {
        $param = $_GET;
        $fields_arr = array('point','predepoit','available_predeposit','available_rc_balance','redpacket','voucher','brokerage');
        $fields_str = trim($param['fields']);
        if ($fields_str) {
            $fields_arr = explode(',',$fields_str);
        }
        $member_info = array();
        if (in_array('point',$fields_arr)) {
            $member_info['point'] = $this->member_info['member_points'];
        }
        if (in_array('predepoit',$fields_arr)) {
            $member_info['predepoit'] = $this->member_info['available_predeposit'];
        }
        if (in_array('available_predeposit',$fields_arr)) {
            $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
            $member_info['freeze_predeposit'] = $this->member_info['freeze_predeposit'];
        }
        if (in_array('available_rc_balance',$fields_arr)) {
            $member_info['available_rc_balance'] = $this->member_info['available_rc_balance'];
        }
        if (in_array('brokerage',$fields_arr)) {
            $member_info['brokerage'] = $this->member_info['brokerage'];
        }
        if (in_array('redpacket',$fields_arr)) {
            $member_info['redpacket'] = Model('redpacket')->getCurrentAvailableRedpacketCount($this->member_info['member_id']);
        }
        if (in_array('voucher',$fields_arr)) {
            $member_info['voucher'] = Model('voucher')->getCurrentAvailableVoucherCount($this->member_info['member_id']);
        }
        output_data($member_info);
    }

    /**
     * 积分转账首页
     */
    public function get_pointOp(){
        $member_info['member_points'] = $this->member_info['member_points'];
        $member_info['user_name'] = $this->member_info['member_name'];
        output_data($member_info);
    }

    /**
     * 积分转账处理
     */
    public function transfer_pointOp(){
          // 接收数据
          $account = $_POST['account'];
          $point = (int)$_POST['points'];

          // 判断积分是否为正整数
          if($point<0){
              $res = array(
                  'code' => 400,
                  'msg'  => "转账积分必须大于0",
              );
              echo json_encode($res);
              die;
          }

          // 验证处理
          if(empty($account)){
                $res = array(
                    'code' => 400,
                    'msg'  => "收款账号不为空",
                );
                echo json_encode($res);
                die;
          }
          if(!preg_match('/^1(3[0-9]|5[012356789]|8[0256789]|7[0678])\d{8}$/',$account, $arr)){
                  $res = array(
                      'code' => 400,
                      'msg'  => "收款账号格式不正确",
                  );
              echo json_encode($res);
              die;
          }
          if(empty($point)){
              $res = array(
                  'code' => 400,
                  'msg'  => "转账积分不能为零",
              );
              echo json_encode($res);
              die;
          }

          if($point>$this->member_info['member_points']){
                  $res = array(
                      'code' => 400,
                      'msg'  => "转账积分不能超过已有积分",
                  );
              echo json_encode($res);
              die;
          }
          // 查询指定账号是否存在
          $res = Model('member')->getMemberInfo(array('member_mobile'=>$account));
          if(empty($res)){
                  $res = array(
                      'code' => 400,
                      'msg'  => "转账账号不存在",
                  );
              echo json_encode($res);
              die;
          }

          // 转账处理
          $my_member_id = $this->member_info['member_id'];

          $updata['member_points'] = intval($res['member_points'])+intval($point);
          $res1 = Model('member')->editMember(array('member_id'=>$res['member_id']),$updata);
          if($res1){
               $myupdata['member_points'] = intval($this->member_info['member_points'])-intval($point);
               Model('member')->editMember(array('member_id'=>$this->member_info['member_id']),$myupdata);
          }
          // 写入记录
          $res_id = $this->writeLogs($my_member_id,$res['member_id'],$account,$point);
          $result = array(
               "code" => 200,
               'id' => $res_id,
               'msg'  => '转账成功'
          );
          echo json_encode($result);
    }

    /**
     * 积分转账记录
     */
    public function transfer_point_logOp(){
        if($_POST['id']){
             $where['id'] = $_POST['id'];
             $log= $this->get_pointLogList($where);
             echo json_encode(array('log'=>$log));
             die;
        }
        $time = getLastTimeArea(date('Y'),date('m'),4,$_GET['curpage']);
        $where['transfer_form_id'] = $this->member_info['member_id'];
        $log_list = [];
        foreach ($time as $v) {
            $where['transfer_time'] = ['between',$v['timeArea']];
            $log['data'] = $this->get_pointLogList($where);
            foreach($log['data'] as $key => $value){
                $log['data'][$key]['transfer_time'] = date("Y-m-d",$value['transfer_time']);
            }

            $log['time'] = $v['date'];
            $log_list[] = $log;
        }
        echo json_encode(array("log_list"=>$log_list));
    }

    /**
     * @param $transfer_form_id 转账人id
     * @param $transfer_to_id 转账指定id
     * @param $point 转账积分
     */
    protected function writeLogs($transfer_form_id,$transfer_to_id,$account,$point){
          $logDatas = array();
          $logDatas['transfer_form_id'] = $transfer_form_id;
          $logDatas['transfer_accept_id'] = $transfer_to_id;
          $logDatas['points'] = $point;
          $logDatas['account'] = $account;
          $logDatas['transfer_time'] = time();
          $res_id = Model('transfer_point_log')->insert($logDatas);
          return $res_id;
    }

    // 根据条件查询
    protected function get_pointLogList($condition){
        $reslute =  Model('transfer_point_log')->where($condition)->select();
        return $reslute;
    }

    // 获取卡号信息
    public function card_infoOp(){
         $condition['member_id'] = $this->member_info['member_id'];
         $data = Model('member_card')->where($condition)->select();
         if($data){
             echo json_encode(array('card_info'=>$data));
         }else{
             echo json_encode(0);
         }
    }

    // 修改卡号
    public function edit_cardOp(){
        // 接收数据
        $name = $_POST['name'];
        $card_num = $_POST['card_num'];
        $bank_account = $_POST['bank_account'];
        $branch_account = $_POST['branch_account'];
        $tel = $_POST['tel'];
        $isedit = $_POST['isedit'];

        if($name==''||$card_num==''||$bank_account==''||$branch_account==''||$tel==''){
                $res = array(
                    "code" =>400,
                    "msg"  =>"卡号信息不能为空"
                );
                echo json_encode($res);
                die;
        }
        if(!preg_match('/^\d{16}|\d{19}$/',$card_num, $arr)){
            $res = array(
                'code' => 400,
                'msg'  => "银行卡格式不正确",
            );
            echo json_encode($res);
            die;
        }

        if(!preg_match('/^1(3[0-9]|5[012356789]|8[0256789]|7[0678])\d{8}$/',$tel, $arr)){
            $res = array(
                'code' => 400,
                'msg'  => "手机号格式不正确",
            );
            echo json_encode($res);
            die;
        }

        // 准备数据
        $data['member_id'] = $this->member_info['member_id'];
        $data['member_name'] = $name;
        $data['card_num'] = $card_num;
        $data['card_bank_account'] = $bank_account;
        $data['card_branch_account'] = $branch_account;
        $data['bank_bind_mobile'] = $tel;
        if($isedit) {
            $res = Model('member_card')->where(array("member_id"=>$this->member_info['member_id']))->update($data);
        }else{
            // 写入数据库
            $res = Model("member_card")->insert($data);
        }
        if($res){
            $res = array(
                'code'=>200,
                'msg' => "银行卡修改成功",
            );
            echo json_encode($res);
        }
    }

    // 得到预存款
    public function get_predepositOp(){
        if($_POST['form']=='member'){
            $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if($_POST['form']=='store'){
            $member_info['available_predeposit'] = $this->member_info['av_store_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if($_POST['form']=='tuiguang'){
            $member_info['available_predeposit'] = $this->member_info['av_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if($_POST['form']=='agent_pt'){
            $member_info['available_predeposit'] = $this->member_info['av_agent_pt_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if($_POST['form']=='agent_sq'){
            $member_info['available_predeposit'] = $this->member_info['av_agent_sq_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if($_POST['form']=='sq'){
            $member_info['available_predeposit'] = $this->member_info['av_sq_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        output_data($member_info);
    }

    // 代理商搜索
    public function agent_seachOp(){
          $addressArr = trim($_GET['address']);
          $type = trim($_GET['type']);
          $model = Model();
          if ($_GET['page']) {
             $page = $_GET['page'];
          } else {
             $page = 1;
          }
          $pagenum = 30;
          $startlimit = ($page - 1) * $pagenum;
          $where['area_info'] = array('like',"%".$addressArr."%");
          $where['type'] = $type;
          $server_list = $model->table('agent')->where($where)->limit("$startlimit,$pagenum")->select();
          output_data(array('server_list'=>$server_list));
    }

    public function shopOp(){
        $log_list = [];
        $where['ob_store_id'] = $_SESSION['store_id'];
        $log['data'] = Model("ag_bill")->where($where)->select();
        $log_list[] = $log;
        output_data(array("log_list"=>$log_list));
    }

    public function businessOp(){
        $log_list = [];
        $where['ob_store_id'] = $_SESSION['store_id'];
        $log['data'] = Model("sq_bill")->where($where)->select();
        foreach($log['data'] as $k => $v){
             $log['data'][$k]['ob_month'] = date('Y年m月',strtotime($v['os_month']."01"));
             $log['data'][$k]['month'] = date('n月',strtotime($v['os_month']."01"));
             $log['data'][$k]['ob_create_time'] = date('Y-m-d',$v['ob_create_date']);
        }
        $log_list[] = $log;
        output_data(array("log_list"=>$log_list));
    }

    // 代理商详情
    public function agent_infoOp(){
        $where['member_id'] = $_GET['agent_id'];
        $data['agent']  = Model('agent')->where($where)->find();
        $data['member'] = Model('member')->where($where)->find();
        output_data(array('data'=>$data));
    }

    /**
     * 提现申请
     */
    public function do_withdrawalOp(){
        $moneynum = intval($_POST['moneynum']);

        if(empty($moneynum)){
              $res = array(
                  'code'=>400,
                  'msg' =>"提现金额不能为空",
              );
              echo json_encode($res);
              die;
        }

        if(!preg_match('/^[0-9]*[0-9]$/',$moneynum,$arr)){
              $res = array(
                   'code' =>400,
                   'msg' =>"提现金额必须为数字"
              );
              echo json_encode($res);
              die;
        }

        if($moneynum%100!=0){
              $res = array(
                  'code' => 400,
                  'msg' => "提现金额必须为100的整数倍",
              ) ;
            echo json_encode($res);
            die;
        }
        // 检测提现类型 下列提现无需检测绑卡状态
        $oparrow = array('tuiguang','store','agent_pt','agent_sq','sq');
        if(!in_array($_POST['op'],$oparrow)) {
            // 查询是否绑定了银行卡
            $member_id = $this->member_info['member_id'];
            $card = Model('member_card')->where(array("member_id" => $member_id))->select();
            if (empty($card)) {
                $res = array(
                    'code' => 401,
                    'msg' => "未绑定银行卡",
                );
                echo json_encode($res);
                die;
            }
        }
        if($_POST['op']=="member"){
            $class =0;
            $updata['available_predeposit'] = $this->member_info['available_predeposit'] - $moneynum;
            $updata['freeze_predeposit'] = $this->member_info['freeze_predeposit'] + $moneynum;
        }
        if($_POST['op']=='store'){
            $class =1;
            $updata['av_store_brokerage'] = $this->member_info['av_store_brokerage'] - $moneynum;
            $updata['store_freeze_brokerage'] = $this->member_info['store_freeze_brokerage'] + $moneynum;
        }
        if($_POST['op']=='tuiguang'){
            $class =2;
            $updata['av_brokerage'] = $this->member_info['av_brokerage'] - $moneynum;
            $updata['freeze_brokerage'] = $this->member_info['freeze_brokerage'] + $moneynum;
        }
        if($_POST['op']=='agent_pt'){
            $class =3;
            $updata['av_agent_pt_brokerage'] = $this->member_info['av_agent_pt_brokerage'] - $moneynum;
            $updata['agent_pt_freeze_brokerage'] = $this->member_info['agent_pt_freeze_brokerage'] + $moneynum;
        }
        if($_POST['op']=='agent_sq'){
            $class =4;
            $updata['av_agent_sq_brokerage'] = $this->member_info['av_agent_sq_brokerage'] - $moneynum;
            $updata['agent_sq_freeze_brokerage'] = $this->member_info['agent_sq_freeze_brokerage'] + $moneynum;
        }
        if($_POST['op']=='sq'){
            $class =5;
            $updata['av_sq_brokerage'] = $this->member_info['av_sq_brokerage'] - $moneynum;
            $updata['sq_freeze_brokerage'] = $this->member_info['sq_freeze_brokerage'] + $moneynum;
        }

        $res = Model('member')->editMember(array('member_id'=>$this->member_info['member_id']),$updata);

        if(!$res){
             $res = array("code"=>400,'msg'=>"提现申请失败");
             echo json_encode($res);
             die;
        }
        // 发起提现申请
        $inserData['order_sn'] = rand(0,1000).time(); // 提现交易号
        $inserData['member_id'] = $this->member_info['member_id'];  // 提现会员id
        $inserData['name'] = $this->member_info['member_name'];
        $inserData['withdrawals_card'] = $card[0]['card_num']; // 提现卡号
        $inserData['cash'] = $moneynum; // 提现金额
        $inserData['state'] = 0; // 提现状态
        $inserData['verification_time'] = '';
        $inserData['class'] = $class;
        $inserData['time'] = time(); // 时间
        $inserData['remarks'] = '';
        $res = Model("cash_withdrawal_apply")->insert($inserData);

        if($res){
              $res = array(
                  'code' => 200,
                  'msg'  => "提现申请发送成功",
              );
              echo json_encode($res);
        }
    }

    // 根据条件查询
    protected function get_withdrawLogList($condition){
        $reslute =  Model('cash_withdrawal_apply')->where($condition)->select();
        return $reslute;
    }

    // 提现记录
    public function cash_withdraw_logOp(){
        $time = getLastTimeArea(date('Y'),date('m'),4,$_GET['curpage']);
        $type = 0;
        if($_POST['name']=='member'){
              $type = 0;
        }
        if($_POST['name']=='tuiguang'){
            $type = 1;
        }
        if($_POST['name']=='store'){
            $type = 2;
        }
        $where['member_id'] = $this->member_info['member_id'];
        $where['class'] = $type;
        $log_list = [];
        foreach ($time as $v) {
            $where['time'] = ['between',$v['timeArea']];
            $log['data'] = $this->get_withdrawLogList($where);
            foreach($log['data'] as $key => $value){
                $log['data'][$key]['time'] = date("Y-m-d",$value['time']);
            }
            $log['time'] = $v['date'];
            $log_list[] = $log;
        }
        echo json_encode(array("log_list"=>$log_list));
    }

    public function agentOp(){
          $member_id = $_SESSION['member_id'];
          $where['member_id'] = $member_id;
          $agent = Model('agent')->where($where)->find();
          $area_info = explode(' ',$agent['area_info']);
          $agent['agent'] = $area_info[$agent['type']-1];
          $agent['total'] = $this->member_info['agent_pt_brokerage'];
          $agent['av_total'] = $this->member_info['av_agent_pt_brokerage'];
          $now_date = date("Y-m-d",time());
          $date = getlastMonthDays($now_date);
          $lastMonth = date("Ym",strtotime($date['0']));
          // 获取店铺信息
          $condition['ob_store_id'] = $_SESSION['store_id'];
          $condition['os_month'] =  $lastMonth;
          $lastMonth_info = Model('sq_bill')->where($condition)->field("ob_result_totals")->find();
          $agent['result_totals'] = $lastMonth_info['ob_result_totals']?$lastMonth_info['ob_result_totals']:0;
          $data['agent'] = $agent;
          output_data($data);
    }

    public function bussOp(){
        $member_id = $_SESSION['member_id'];
        $where['member_id'] = $member_id;
        $agent = Model('agent')->where($where)->find();
        $area_info = explode(' ',$agent['area_info']);
        $agent['agent'] = $area_info[$agent['type']-1];
        $agent['total'] = $this->member_info['agent_sq_brokerage'];
        $agent['av_total'] = $this->member_info['av_agent_sq_brokerage'];
        $now_date = date("Y-m-d",time());
        $date = getlastMonthDays($now_date);
        $lastMonth = date("Ym",strtotime($date['0']));
        // 获取店铺信息
        $condition['ob_store_id'] = $_SESSION['store_id'];
        $condition['os_month'] =  $lastMonth;
        $lastMonth_info = Model('sq_bill')->where($condition)->field("ob_result_totals")->find();
        $agent['result_totals'] = $lastMonth_info['ob_result_totals']?$lastMonth_info['ob_result_totals']:0;
        $data['agent'] = $agent;
        output_data($data);
    }

    public function sq_brokerageOp(){
         $data['sq']['total'] = $this->member_info['sq_brokerage'];
         $data['sq']['av_borkerage'] = $this->member_info['av_sq_brokerage'];
         output_data($data);
    }

    public function sq_brokerageListOp(){
        $time = getLastTimeArea(date('Y'),date('m'),4,$_GET['curpage']);
        $where['store_id'] = $_SESSION['store_id'];
        $log_list = [];
        foreach ($time as $v) {
            $where['addtime'] = ['between',$v['timeArea']];
            $log['data'] = $this->get_sqLogList($where);
            foreach($log['data'] as $key => $value){
                $log['data'][$key]['addtime'] = date("Y-m-d",$value['addtime']);
            }
            $log['time'] = $v['date'];
            $log_list[] = $log;
        }
        $data['log_list'] = $log_list;
        output_data($data);
    }

    // 根据条件查询
    protected function get_sqLogList($condition){
        $reslute =  Model('sq_brokerage_log')->where($condition)->select();
        return $reslute;
    }
}
